package com.fanfq.util.download;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.fanfq.smplayer.SMPlayerApplication;

import android.os.Environment;

public class FileUtils {
	private String SDPATH;
	
	private int FILESIZE = 1024; 
	
	
	public String getSDPATH(){
		return SDPATH;
	}
	
	public FileUtils(){
		SDPATH = SMPlayerApplication.ROOT_SDCARD_PATH;
	}
	
	/**
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public File createSDFile(String fileName) throws IOException{
		File file = new File(fileName);
		file.createNewFile();
		return file;
	}
	
	/**
	 * @param dirName
	 * @return
	 */
	public File createSDDir(String dirName){
		File dir = new File(dirName);
		dir.mkdir();
		return dir;
	}
	
	/**
	 * @param fileName
	 * @return
	 */
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	/**
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 */
	public File write2SDFromInput(String fileName,InputStream input){
		File file = null;
		OutputStream output = null;
		try {
			//createSDDir(path);
			file = createSDFile(fileName);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[FILESIZE];
			int length;
			while((length=(input.read(buffer))) >0){
				output.write(buffer,0,length);
			}
			output.flush();
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

}
